import Request from '@/js_sdk/luch-request/index.js'
import { BASE_API } from './url.js'

import { userStorage } from '@/hooks/useStorage';
const { getStorage, removeStorage } = userStorage();

if (process.env.NODE_ENV == 'development') {
	console.log(`%c api_path ${BASE_API}`,
		'background:#5ac725;padding:0 5px 1px 0;border-radius: 3px 0 0 3px;  color: #ffffff')
}
const apiPath = BASE_API
// 获取token
const getTokenStorage = () => {
	const token = getStorage('token')
	if (token) {
		return token
	} else {
		return ''
	}
}

// 请求
const http = new Request()
http.setConfig((config : any) => {
	config.baseURL = `${BASE_API}`;
	config.withCredentials = false;
	config.custom.auth = true;
	config.custom.catch = true;
	config.custom.toast = true;
	config.custom.loading = false;
	return config
})

http.interceptors.request.use((config) => {
	config.data = config.data || {}

	if (config.custom.toast) uni.hideToast()
	if (config.custom.loading) uni.showLoading()
	if (config.custom.auth) {
		config.header['authorization'] = getTokenStorage() && `Bearer ${getTokenStorage()}` || "";
	} else {
		config.header['Content-Type'] = 'application/x-www-form-urlencoded'
		if (config.method === 'GET' || config.method === 'DELETE') {
			config.params = {
				...config.params,
				token: getTokenStorage()
			}
		} else if (config.method === 'POST' || config.method === 'PUT') {
			config.data = {
				...config.data,
				token: getTokenStorage()
			}
		}
	}

	// 如果token不存在，return Promise.reject(config) 会取消本次请求
	//  if (!token) { 
	//    return Promise.reject(config)
	//  }
	return config
}, (config : any) => {
	return Promise.reject(config)
})

http.interceptors.response.use(async (response) => {
	/* 请求之后拦截器。可以使用async await 做异步操作  */
	if (response.config.custom.loading) uni.hideLoading()

	if (response.statusCode !== 200) {
		return Promise.reject(response)
	} else {
		const data = response.data
		if (data.code == 0) {
			response.config.custom?.toast && uni.showToast({
				title: data.msg || data.message,
				icon: 'none',
				duration: 2000
			})
			if (response.config.custom?.catch) {
				return Promise.reject(data)
			} else {
				return Promise.resolve(data)
			}
		} else if (data.code == -1) {
			uni.showToast({
				title: '未登录',
				icon: 'none',
				duration: 1500
			})
			removeStorage('token');
			removeStorage('userInfo');
			uni.reLaunch({
				url: '/pages/login/login'
			})
			return Promise.reject(response.data)
			// return false
		} else {
			return Promise.resolve(data)
		}
	}
	return response
}, (response : any) => {
	return Promise.reject(response)
})
// 上传 
function http_upload({
	loading = true,
	header_token = true,
	url = '/admin/tool/uploadImage',
	file, // 假设file是一个File对象，但它是可选的  
	filePath, // filePath是文件的本地路径，也是可选的，但通常你需要它 
	name = 'file',
	formData
} : { [key : string] : any }) {
	loading && uni.showLoading()
	return new Promise((resolve, reject) => {
		interface Headers { authorization ?: string }
		let header : Headers = {}
		interface FormData { token ?: string }
		let formData : FormData = {}
		if (header_token) {
			header.authorization = `Bearer ${getTokenStorage()}`
		} else {
			formData.token = getTokenStorage()
		}
		uni.uploadFile({
			url: `${BASE_API}${url}`,
			fileType: 'image',
			file,
			filePath,
			name,
			formData,
			header,
			success: res => {
				// console.log('uploadFile', res)
				loading && uni.hideLoading();
				const imgRes = JSON.parse(res.data)
				if (imgRes.code == 1) {
					resolve(imgRes)
				} else {
					reject({ code: 0, msg: '失败' });
				}
			},
			fail: err => {
				loading && uni.hideLoading();
				reject({ code: 0, msg: '失败' });
			}
		});
	})
}
export {
	apiPath,
	http,
	http_upload
}